<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>游戏房间</title>
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/game_room.css">
</head>
<body>
    <div class="nav">网络五子棋对战游戏</div>
    <div class="container">
        <div id="chess_area">
            <!-- 棋盘区域, 需要基于 canvas 进行实现 -->
            <canvas id="chess" width="450px" height="450px"></canvas>
            <!-- 显示区域 -->
            <div id="screen"> 等待玩家连接中... </div>
        </div>
        <div id="chat_area" width="400px" height="300px">
            <div id="chat_show">
                <!-- <p id="self_msg">你好！</p></br> -->
                <!-- <p id="peer_msg">你好！</p></br> -->
            </div>
            <div id="msg_show">
                <input type="text" id="chat_input">
                <button id="chat_button">发送</button>
            </div>
        </div>
    </div>
    <script>
        let chessBoard = [];
        let BOARD_ROW_AND_COL = 15;
        let chess = document.getElementById('chess');
        //获取chess控件区域2d画布
        let context = chess.getContext('2d');

        var screen = document.getElementById("screen");
        var chat_button = document.getElementById("chat_button");

        var ws_url = "ws://" + location.host + "/room";
        var ws_hdl = new WebSocket(ws_url);
        var is_white = false;
        var my_round = false;
        var room_info = null;
        
        function initGame() {
            initBoard();
            // 背景图片
            let logo = new Image();
            logo.src = "image/sky.jpeg";
            logo.onload = function () {
                // 绘制图片
                context.drawImage(logo, 0, 0, 450, 450);
                // 绘制棋盘
                drawChessBoard();
            }
        }
        function initBoard() {
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                chessBoard[i] = [];
                for (let j = 0; j < BOARD_ROW_AND_COL; j++) {
                    chessBoard[i][j] = 0;
                }
            }
        }
        // 绘制棋盘网格线
        function drawChessBoard() {
            context.strokeStyle = "#BFBFBF";
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                //横向的线条
                context.moveTo(15 + i * 30, 15);
                context.lineTo(15 + i * 30, 430); 
                context.stroke();
                //纵向的线条
                context.moveTo(15, 15 + i * 30);
                context.lineTo(435, 15 + i * 30); 
                context.stroke();
            }
        }
        //绘制棋子
        function oneStep(i, j, isWhite) {
            if (i < 0 || j < 0) return;
            context.beginPath();
            context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
            context.closePath();
            //createLinearGradient() 方法创建放射状/圆形渐变对象
            var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
            // 区分黑白子
            if (!isWhite) {
                gradient.addColorStop(0, "#0A0A0A");
                gradient.addColorStop(1, "#636766");
            } else {
                gradient.addColorStop(0, "#D1D1D1");
                gradient.addColorStop(1, "#F9F9F9");
            }
            context.fillStyle = gradient;
            context.fill();
        }
        //棋盘区域的点击事件
        chess.onclick = function (e) {
            if (!my_round)
            {
                alert("等待对方走棋...");
                return;
            }
            let x = e.offsetX;
            let y = e.offsetY;
            // 注意, 横坐标是列, 纵坐标是行
            // 这里是为了让点击操作能够对应到网格线上
            let col = Math.floor(x / 30);
            let row = Math.floor(y / 30);
            // if (chessBoard[row][col] != 0) {
            //     alert("当前位置已有棋子！");//当前位置是否被占用可以交给服务器判断 也可以在前端多判断一次
            //     return;
            // }
            //oneStep(col, row, true);//绘制棋子

            //向服务器发送走棋请求
            send_put_chess_req(row, col);
        }

        //聊天发送按钮的点击事件
        chat_button.onclick = function() {
            send_chat_req();
        }

        function send_chat_req()
        {
            var req = {
                optype: "chat",
                room_id: room_info.room_id,
                uid: room_info.uid,
                message: document.getElementById("chat_input").value,
            }
            console.log(JSON.stringify(req));
            ws_hdl.send(JSON.stringify(req));
        }

        function send_put_chess_req(r, c)
        {
            var req = {
                optype: "put_chess",
                room_id: room_info.room_id,
                uid: room_info.uid,
                row: r,
                col: c,
            }
            console.log(JSON.stringify(req));
            ws_hdl.send(JSON.stringify(req));
        }
        

        window.onbeforeunload = function() {
            //游戏大厅页面关闭/跳转时的回调函数 断开websocket连接 
            ws_hdl.close();
        }

        ws_hdl.onopen = ws_onopen;
        ws_hdl.onclose = ws_onclose;
        ws_hdl.onerror = ws_onerror;
        ws_hdl.onmessage = ws_onmessage;

        function ws_onopen() { console.log("websocket onopen"); }
        function ws_onclose() { console.log("websocket onclose"); }
        function ws_onerror() { console.log("websocket onerror"); }
        function ws_onmessage(evt)
        {
            //收到进入房间成功的响应后初始化房间页面
            var res = JSON.parse(evt.data);
            console.log(evt.data);
            if (res.result == false && res.uid == room_info.uid)//响应结果错误 且该响应由己方造成
            {
                alert(res.reason);
                return;
            }
            if (res.result == false)//响应结果错误 该响应由对方造成
                return;//忽略该响应
            if (res.optype == "enter_room")
            {
                room_info = res;//保存房间信息到全局
                initGame();
                is_white = room_info.white_id == room_info.uid ? true : false;//我方棋子是否是白棋
                my_round = is_white ? true : false;//我方为白棋则初始为我方回合 我方为黑棋则初始为对方回合
                if (my_round)
                    screen.innerHTML = "轮到我方走棋...";
                else
                    screen.innerHTML = "轮到对方走棋...";
            }
            else if (res.optype == "put_chess")//收到己方/对方的走棋消息
            {
                if (res.reason == "对方掉线，不战而胜") 
                {
                    alert(res.reason);//对方掉线 不战而胜
                    var chess_area = document.getElementById("chess_area");
                    var button = document.createElement("div");
                    button.innerHTML = "返回游戏大厅";
                    button.onclick = function () {
                        location.replace("/game_hall.html");
                    }
                    chess_area.appendChild(button);
                    screen.innerHTML = res.reason;
                    return;
                }

                if (res.uid == room_info.uid)//当前这步棋是我方下的
                {
                    oneStep(res.col, res.row, is_white);//绘制我方棋子
                    my_round = false;
                }
                else
                {
                    oneStep(res.col, res.row, !is_white);//绘制对方棋子
                    my_round = true;
                }
                chessBoard[res.row][res.col] = 1;//服务器中1表示白棋 而前端页面只需要知道该位置有没有棋子 不需要知道棋子颜色 因为前端不判输赢
                
                if (res.winner == 0) 
                {
                    if (my_round)
                        screen.innerHTML = "轮到我方走棋...";
                    else
                        screen.innerHTML = "轮到对方走棋...";
                    return;
                }

                if (res.winner == room_info.uid)
                    screen.innerHTML = "己方五星连珠, 战无敌";
                else
                    screen.innerHTML = "对方五星连珠, 虽败犹荣";

                //分出胜负 游戏结束 添加返回大厅按钮
                var chess_area = document.getElementById("chess_area");
                var button = document.createElement("div");
                button.innerHTML = "返回游戏大厅";
                button.onclick = function() {
                    ws_hdl.close();
                    location.replace("/game_hall.html");
                }
                chess_area.appendChild(button);
            }
            else if (res.optype == "chat")//收到己方/对方的聊天消息
            {
                var chat_show = document.getElementById("chat_show");
                var msg = document.createElement("p");
                var br = document.createElement("br");
                if (res.uid == room_info.uid)//当前聊天消息是己方发送的
                    msg.setAttribute("id", "self_msg");
                else
                    msg.setAttribute("id", "peer_msg");
                msg.innerHTML = res.message;
                chat_show.appendChild(msg);
                chat_show.appendChild(br);
                document.getElementById("chat_input").value = "";
            }
        }
    </script>
</body>
</html>